#!/usr/bin/env bash

# ===========================================================================
# File: "restartAlpha"
#                        Created: 2020-09-18 21:16:56
#              Last modification: 2020-09-19 07:16:10
# 
# Usage: 
#     restartAlpha ?path? ?delay?
#     restartAlpha -v
# 
# Author: Bernard Desgraupes
# e-mail: <bdesgraupes@users.sourceforge.net>
# Copyright (c) 2020 Alpha Cabal
# All rights reserved.
# This file is part of the AlphaCocoa project.
# ===========================================================================

ALF_VERSION="0.1"

# Initialization
ALF_DEBUG=1
ALF_DELAY=2
ALF_PATH=/Applications/Alpha.app
ALF_LOG_DIR=~/Library/Logs/Alpha
ALF_LOG_FILE=$ALF_LOG_DIR/restartAlpha.log

if ! [ -e $ALF_LOG_FILE ] ; then
	mkdir $ALF_LOG_DIR
	touch $ALF_LOG_FILE
fi

loginfo () {
	if [ $ALF_DEBUG == 1 ] ; then
		echo "$1" >> $ALF_LOG_FILE
	fi
}

logdate () {
	loginfo "----------------------------------------------------------------------"
	loginfo "date: `date "+%Y-%m-%d %H:%M:%S"`"
}

if [ $# == 1 ] ; then
	if [ $1 == "-v" ] ; then
		echo $ALF_VERSION
		exit 0
	elif [ $1 == "-h" ] ; then
		echo "Usage: $(basename $0) ?path? ?delay?"
		exit 0
	fi	
fi

if [ $# -gt 0 ] ; then
	ALF_PATH=$1
fi
if [ $# -gt 1 ] ; then
	ALF_DELAY=$2
fi

logdate
loginfo "delay: $ALF_DELAY"
loginfo "path: $ALF_PATH"

ALF_NAME=${ALF_PATH##*/}
if [ "$ALF_NAME" != "Alpha.app" ] ; then
	loginfo "-> not an Alpha path"
	result=1
elif ! [ -e $ALF_PATH ] ; then
	loginfo "-> can't find $ALF_PATH"
	result=1
else
	sleep $ALF_DELAY
	open $ALF_PATH
	result=$?
fi

loginfo "exit: $result"

exit $result
